package com.lhl.cp.controller;

import cn.hutool.json.JSONUtil;
import com.lhl.cp.domain.vo.AuthVo;
import com.lhl.jwt.utils.JwtUtil;
import com.lhl.wx.cp.autoconfigure.WxCpConfiguration;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpMaJsCode2SessionResult;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @className: WxCpOAuthController
 * @description: 根据code获得用户信息
 * @author: king
 * @date: 2020-09-17 16:48
 **/
@RestController
@Slf4j
@RequestMapping("/cp/userInfo/{agentId}")
public class WxCpController {
    public static final String AUTHORIZATION_HEADER = "Authorization";
    public static final String AUTHORIZATION_START_STRING = "Bearer ";
    @Value("${user.login.url:http://tgw.qipai.com.cn:6121/}")
    private String reqUrl;

    /**
     * 小程序
     * @param agentId
     * @param code
     * @return
     * @throws WxErrorException
     */
    @GetMapping
    public WxCpUser getUserInfo(@PathVariable Integer agentId, @RequestParam String code, HttpServletResponse response) throws WxErrorException {
        log.debug("-----------------------------------------------------------");
        log.debug("code == {}",code);
        log.debug("reqUrl == {}",reqUrl+"uc/token/wx/auth");
        WxCpMaJsCode2SessionResult sessionResult = WxCpConfiguration.getCpService(agentId).jsCode2Session(code);
        log.debug("sessionResult == {}", JSONUtil.toJsonStr(sessionResult));
        WxCpUser user = WxCpConfiguration.getCpService().getUserService().getById(sessionResult.getUserId());
        log.debug("user==={}", JSONUtil.toJsonPrettyStr(user));
        String token = JwtUtil.createToken(user.getUserId());
        response.setHeader(AUTHORIZATION_HEADER, AUTHORIZATION_START_STRING + token);
        return user;
    }

    /**
     * 一般应用
     * @param
     * @param
     * @return
     * @throws WxErrorException
     */
    /*@GetMapping(produces = "text/plain;charset=utf-8")
    public ResponseEntity<Map> getUserInfoByH5(@PathVariable Integer agentId, @RequestParam String code) throws WxErrorException {
        log.debug("-----------------------------------------------------------");
        log.debug("code == {}",code);
        log.debug("reqUrl == {}",reqUrl+"uc/token/wx/auth");
        WxUserInfo wxUserInfo = new WxUserInfo();
        WxCpOauth2UserInfo wxCpOauth2UserInfo = WxCpConfiguration.getCpService(agentId).getOauth2Service().getUserInfo(code);
        log.debug("wxCpOauth2UserInfo == {}", JSONUtil.toJsonStr(wxCpOauth2UserInfo));
        WxCpUser user = WxCpConfiguration.getCpService().getUserService().getById(wxCpOauth2UserInfo.getUserId());
        log.debug("user==={}", JSONUtil.toJsonPrettyStr(user));
        return sendLogin(StrUtil.isNotBlank(user.getMobile())?user.getMobile():user.getUserId());
    }*/

    private ResponseEntity<Map> sendLogin(String account){
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        AuthVo vo = new AuthVo();
        vo.setAccount(account);
        vo.setPassword("");
        vo.setAppId("qipai_app");
        vo.setAppmac("wx_TEST");


        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<AuthVo> request = new HttpEntity<>(vo, headers);

        ResponseEntity<Map> response = restTemplate.postForEntity( "http://tgw.qipai.com.cn:6121/uc/token/wx/auth", request , Map.class );
        log.debug("response=={}", JSONUtil.toJsonStr(response.getBody()));
        return response;
    }
}